﻿
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;

namespace JsonRpc
{
    public class JsonRpcClient
    {
        private IPEndPoint _remote;

        public JsonRpcClient(string ip, int port) {
            this._remote = new IPEndPoint(IPAddress.Parse(ip), port);
        }

        public IPEndPoint RemoteEndPoint { get { return _remote; } }

        public T Call<T>(JsonRequest req) {
            using (var s = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)) {
                s.Connect(_remote);
                s.Send(Encoding.UTF8.GetBytes(req.ToJsonString()));
                var buffer = new byte[1024];
                var i = s.Receive(buffer);
                var rp = Encoding.UTF8.GetString(buffer, 0, i);
                var ro = Newtonsoft.Json.JsonConvert.DeserializeObject<JsonResponse<T>>(rp);
                if (string.IsNullOrEmpty(ro.Error)) {
                    return ro.Result;
                }
                throw new Exception(ro.Error);
            }
        }


    }
}
